package com.a3dweijing.wetouch2.Activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.a3dweijing.wetouch2.Common.CallBack;
import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.Util.GlideUtil;
import com.a3dweijing.wetouch2.Util.PermissionapplicationHelp;
import com.a3dweijing.wetouch2.Util.ProgressDialogHelp;
import com.a3dweijing.wetouch2.Util.Util;
import com.a3dweijing.wetouch2.base.BaseActivity;
import com.a3dweijing.wetouch2.bean.ResultMsg;
import com.a3dweijing.wetouch2.datasave.Singleton;
import com.a3dweijing.wetouch2.network.CommObserver;
import com.a3dweijing.wetouch2.network.Commsubscribe;
import com.a3dweijing.wetouch2.network.RetrofitUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import me.iwf.photopicker.PhotoPicker;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Retrofit;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class ApplyForExpertsActivitiy extends BaseActivity
{
    
    @BindView(R.id.back)
    ImageView back;
    
    @BindView(R.id.top_text)
    TextView topText;
    
    @BindView(R.id.top_right)
    TextView topRight;
    
    @BindView(R.id.top_all)
    RelativeLayout topAll;
    
    @BindView(R.id.tv)
    TextView tv;
    
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    
    @BindView(R.id.iv_rit)
    ImageView ivRit;
    
    @BindView(R.id.rg)
    RadioGroup rg;
    
    /**
     * 判断照片对应的控件
     */
    private int position = 0;
    
    private int rbIsCheck = 1;
    
    private String url1, url2;
    
    private ProgressDialog dialog;
    
    private static String[] PERMISSIONS_STORAGE =
        {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
    
    private int[] id;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_for_experts_activitiy);
        ButterKnife.bind(this);
        initView();
        setOnClick();
    }
    
    private void setOnClick()
    {
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i)
            {
                if (i == R.id.rb1)
                    rbIsCheck = 1;
                else
                    rbIsCheck = 2;
            }
        });
    }
    
    private void isInformation()
    {
        for (int i = 0; i < id.length; i++)
        {
            View viewById = findViewById(id[i]);
            EditText et = viewById.findViewById(R.id.et_rit);
            if (TextUtils.isEmpty(et.getText().toString().trim()))
            {
                Toast.makeText(this, "您有信息还未填写", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(url1) || TextUtils.isEmpty(url2))
            {
                Toast.makeText(this, "您的照片未上传", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        submit();
        
    }
    
    private void submit()
    {
        HashMap<String, RequestBody> map = new HashMap<>();
        RetrofitUtil instance = RetrofitUtil.getInstance();
        map.put("user_id", instance.getBodyBuDate(Singleton.getInstance().getUser().getUser_id()));
        map.put("name", instance.getBodyBuDate(getEtString(id[0])));
        map.put("age_limit", instance.getBodyBuDate(getEtString(id[1])));
        map.put("certificate_code", instance.getBodyBuDate(getEtString(id[2])));
        map.put("aptitude_code", instance.getBodyBuDate(getEtString(id[3])));
        map.put("identity_card", instance.getBodyBuDate(getEtString(id[4])));
        map.put("apply_type", instance.getBodyBuDate(rbIsCheck + ""));
        File file1 = new File(url1);
        File file2 = new File(url2);
        MultipartBody.Part positive_img = RetrofitUtil.getInstance().getBodyByFile("positive_img", file1);
        MultipartBody.Part back_img = RetrofitUtil.getInstance().getBodyByFile("back_img", file2);
        Observable<ResultMsg> observable =
            RetrofitUtil.getInstance().getApiOfPhp().healthConsultant(map, positive_img, back_img);
        new Commsubscribe<ResultMsg>().createSubscribe(observable, dialog, null, disposables, this, new CallBack()
        {
            @Override
            public void doNext(int what, Object obj)
            {
                ResultMsg msg = (ResultMsg)obj;
                Toast.makeText(ApplyForExpertsActivitiy.this, msg.getMessage(), Toast.LENGTH_SHORT).show();
                if (msg.isFlag())
                    finish();
            }
        });
    }
    
    private String getEtString(int id)
    {
        EditText viewById = findViewById(id).findViewById(R.id.et_rit);
        return viewById.getText().toString();
    }
    
    private void initView()
    {
        topText.setText("申请成为专家顾问");
        dialog = ProgressDialogHelp.create(this, "提示", "提交中...", false);
        ivLeft.setImageDrawable(getResources().getDrawable(R.drawable.apply_lefit));
        ivRit.setImageDrawable(getResources().getDrawable(R.drawable.apply_rit));
        String s[] = new String[] {"姓名：", "从业年龄：", "执业证编码：", "资格证编码：", "身份证号码："};
        String hi[] = new String[] {"请输入姓名", "请输入从业年龄", "请输入执业证编码", "请输入资格证编码", "请输入身份证号码"};
        id = new int[] {R.id.name, R.id.age, R.id.code1, R.id.code2, R.id.number};
        for (int i = 0; i < id.length; i++)
        {
            View viewById = findViewById(id[i]);
            TextView tv = viewById.findViewById(R.id.tv_left);
            tv.setText(s[i]);
            EditText et = viewById.findViewById(R.id.et_rit);
            et.setHint(hi[i]);
            switch (i)
            {
                case 1:
                    et.setInputType(InputType.TYPE_CLASS_NUMBER);
                    break;
            }
        }
    }
    
    @OnClick({R.id.iv_left, R.id.iv_rit, R.id.submit})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.iv_left:
                position = 1;
                isPermissions();
                break;
            case R.id.iv_rit:
                position = 2;
                isPermissions();
                break;
            case R.id.submit:
                if (Util.isFastClick())
                {
                    isInformation();
                }
                break;
        }
    }
    
    private void isPermissions()
    {
        int permissionapplication = PermissionapplicationHelp
            .Permissionapplication(this, "android.permission.WRITE_EXTERNAL_STORAGE", PERMISSIONS_STORAGE);
        if (permissionapplication == PERMISSION_GRANTED)
        {
            photpicker();
        }
        else
        {
            Toast.makeText(this, "无使用权限,请同意该权限", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void photpicker()
    {
        PhotoPicker.builder().setPhotoCount(1).setShowCamera(true).setShowGif(true).setPreviewEnabled(true).start(this,
            PhotoPicker.REQUEST_CODE);
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE)
        {
            if (data != null)
            {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                if (photos != null && photos.size() > 0)
                {
                    if (position == 1)
                    {
                        url1 = photos.get(0);
                        GlideUtil.getInstance().showImage(ApplyForExpertsActivitiy.this, url1, ivLeft);
                    }
                    else if (position == 2)
                    {
                        url2 = photos.get(0);
                        GlideUtil.getInstance().showImage(ApplyForExpertsActivitiy.this, url2, ivRit);
                    }
                }
            }
        }
    }
}
